#!/bin/bash
function install_csvn() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装CollabNet Subversion Edge${nocolor}"
    echo ""
    rm -rf /tmp/.csvn.err.info
    csvnHome="$workHome/packages/csvn"
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    
    echo -ne "${blue}安装目录设置${nocolor}
-------------------------------------
设置CollabNet SVN安装目录
最终安装位置为:{设定的安装目录}/csvn
-------------------------------------
输入csvn安装目录[/usr/local]: "
    read -e csvnPath
    csvnPath=${csvnPath:-/usr/local}
    csvnPath=`echo $csvnPath`
    csvnPath=${csvnPath%/}
    echo ""
    
    isNull=`ls $csvnPath/csvn/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        echo -ne "$Warn 目录下存在csvn文件夹，且不为空，继续安装会删除已有数据！\n继续[Yy,Enter],退出[Nn]: "
        read isYn
        if [[ $isYn == [Nn] ]];then
           sleep 0.5
           return 1
        fi
        echo ""
    fi
    
    csvnPort_control=
    PortUsed=
    PortUsed_Pro=
    echo -e "${blue}CSVN管理端口设置${nocolor}
---------------------------------------
通过访问管理服务可配置SVN相关配置，如:
SVN服务端口、SVN备份、SVN仓库权限管理等
请使用>1024的端口，否则服务无法正常运行
---------------------------------------"
    while [[ ! "$csvnPort_control" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        echo -ne "输入csvn管理端口[3343]: "
        read csvnPort_control
        csvnPort_control=${csvnPort_control:-3343}
        csvnPort_control=`echo $csvnPort_control`
        if [[ ! "$csvnPort_control" =~ ^[1-9][0-9]+$ ]];then
             echo -e "$Warn csvn管理端口只能为两位及以上且不以0开头的数字组成，请重新输入！"
             sleep 0.5
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${csvnPort_control} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  echo -e "$Warn csvn管理端口已被使用，请重新输入！"
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    echo ""

    csvnSSLPort_control=`expr $csvnPort_control + 1091`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${csvnSSLPort_control} "`
        while [[ -n $PortUsed_Pro ]]
        do
          csvnSSLPort_control=`expr $csvnSSLPort_control + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${csvnSSLPort_control} "`
        done
    fi

    csvnPort=
    PortUsed=
    PortUsed_Pro=
    echo -e "${blue}SVN服务端口设置${nocolor}
-------------------------------------------
SVN端口，即提供SVN服务端口
默认使用HTTPS提供SVN服务
请使用>1024的端口，除非你使用80或者443端口
-------------------------------------------"
    while [[ ! "$csvnPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        echo -ne "输入SVN服务端口[443]: "
        read csvnPort
        csvnPort=${csvnPort:-443}
        csvnPort=`echo $csvnPort`
        if [[ ! "$csvnPort" =~ ^[1-9][0-9]+$ ]];then
             echo -e "$Warn SVN服务端口只能为两位及以上且不以0开头的数字组成，请重新输入！"
             sleep 0.5
        fi
        if [ "$PortCheck" == "Yes" ];then
           PortUsed_Pro=`$listen_cmd 2>/dev/null|grep ":${csvnPort} "`
           if [ -n "$PortUsed_Pro" ];then
               PortUsed=Yes
               echo -e "$Warn SVN服务端口已被使用，请重新输入！"
           else
               PortUsed=No
           fi
        else
           PortUsed=No
        fi
    done
    echo ""
    
    csvnUser=
    echo -ne "${blue}CSVN服务运行用户${nocolor}
-----------------------------------
运行CSVN服务进程，需要的用户
不能使用ROOT用户，否则无法启动服务
-----------------------------------
请输入csvn运行用户[svnuser]: " 
    read csvnUser
    csvnUser=${csvnUser:-svnuser}
    csvnUser=`echo $csvnUser`
    echo ""

    source /etc/profile >/dev/null 2>&1
    source ~/.bash_profile >/dev/null 2>&1
    source ~/.bashrc >/dev/null 2>&1
    javaPath=`command -v java`
    if [ -z "$javaPath" ];then
        echo -ne "$Info 系统未找到到java命令，请手动输入java命令路径: "
        read -e javaPath
    else
        echo -ne "系统检测到java命令路径为$javaPath\n如果你的CSVN版本比较旧，建议使用JAVA7或6，新版本的JDK可能导致CSVN无法正常工作\n确认[Yy,Enter],修改[Mm]: "
        read isMm
        if [[ $isMm == [Mm] ]];then
          echo -ne "请输入java命令位置: "
          read -e javaPath
        fi
    fi
    javaPath=`echo $javaPath`
    echo ""
    
    javaOut=`$javaPath -version 2>&1|grep 'version "'`
    if [ -z "$javaOut" ];then
        echo -e "$Error java命令不存在或者不可执行，退出csvn安装！"
        anykeyback
        return 1
    fi
    
    # java版本信息
    java_version=$($javaPath -version 2>&1|head -n 1)
    
    echo -ne "${blue}CSVN安装信息汇总${nocolor}
---------------------------------------
csvn安装位置：$csvnPath
csvn管理端口：$csvnPort_control
SVN服务端口：$csvnPort
csvn运行用户：$csvnUser
JAVA命令：$javaPath
JDK版本信息：$java_version
---------------------------------------
继续[Yy,Enter],退出[Nn]: "
    read isYn
    [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
    echo ""
    
    echo ""
    echo -e "${cyan}将开始CSVN安装过程${nocolor}"
    echo ""
    
    echo -e "$Info ${purple}创建csvn运行用户${nocolor}"
    csvnUserPw=`strings /dev/urandom |grep -o '[[:alnum:]_%@!]'|head -n 25|tr -d '\n'`
    isExistU=`cat /etc/passwd|grep "^$csvnUser:"`
    if [ -z "$isExistU" ];then
        /usr/sbin/useradd $csvnUser
        echo "$csvnUserPw"|passwd --stdin $csvnUser
    else
        if [ "$csvnUser" != "root" ];then
         /usr/sbin/usermod -s /bin/bash $csvnUser
         echo "$csvnUserPw"|passwd --stdin $csvnUser
        fi
    fi
    
    echo -e "$Info ${purple}开始安装csvn${nocolor}"
    rm -rf $csvnPath/csvn
    if [ ! -d $csvnPath ];then
        mkdir -p $csvnPath >/dev/null 2>&1
        chown -R $csvnUser:$csvnUser $csvnPath >/dev/null 2>&1
    fi
    csvnPack=`ls -r $csvnHome/ 2>/dev/null |grep CollabNetSubversionEdge.*.tar.gz|head -n 1`
    cd $csvnHome
    tar zxf $csvnPack -C $csvnPath >/dev/null
    if [ "$?" != "0" ];then
        echo -e "$Error csvn安装包损坏，解压失败"
        anykeyback
        return 1
    fi
    
    real_javaPath=$(readlink -f $javaPath)
    javaHome=${real_javaPath%%/bin/*}
    echo -e "$Info ${purple}初始化CSVN管理服务，此过程大概需要2分钟左右${nocolor}"
    cd $csvnPath/csvn/
    mkdir $csvnPath/csvn/tmp
    /bin/mv -f /etc/init.d/csvn /etc/init.d/csvn-1 >/dev/null 2>&1
    /bin/mv -f /etc/init.d/csvn-httpd /etc/init.d/csvn-httpd-1 >/dev/null 2>&1
    chkconfig csvn-1 on >/dev/null 2>&1
    chkconfig csvn-httpd-1 on >/dev/null 2>&1
    ./bin/csvn install >/dev/null 2>&1
    sed -i "s#localhost:3343#$ipaddr:$csvnPort_control#g" $csvnPath/csvn/data/conf/csvn.conf
    sed -i "s#.*JAVA_HOME=.*#JAVA_HOME=$javaHome#g" $csvnPath/csvn/data/conf/csvn.conf
    sed -i "s/.*RUN_AS_USER=.*/RUN_AS_USER=$csvnUser/g" $csvnPath/csvn/data/conf/csvn.conf
    sed -i "s/Djetty.port=.*/Djetty.port=$csvnPort_control/g" $csvnPath/csvn/data/conf/csvn-wrapper.conf
    sed -i "s/Djetty.ssl.port=.*/Djetty.ssl.port=$csvnSSLPort_control/g" $csvnPath/csvn/data/conf/csvn-wrapper.conf
    cat >>$csvnPath/csvn/appserver/start.ini<<EOF
-Djava.io.tmpdir=$csvnPath/csvn/tmp
-Djava.library.path=$csvnPath/csvn/lib
EOF
    chown -R $csvnUser:$csvnUser $csvnPath/csvn/
    $csvnPath/csvn/bin/csvn install >/dev/null 2>&1
    $csvnPath/csvn/bin/csvn start
    curl -s -I --fail http://$ipaddr:$csvnPort_control/csvn >/dev/null 2>&1
    run_status="$?"
    n=0
    while [ "$run_status" != "0" ]
    do
        sleep 1
        let n+=1
        curl -s -I --fail http://$ipaddr:$csvnPort_control/csvn >/dev/null 2>&1
        run_status="$?"
        if [ $n -gt 15 ];then
            break
        fi
    done
    /etc/init.d/csvn stop >/dev/null 2>&1
    $csvnPath/csvn/bin/csvn install >/dev/null 2>&1

    echo -e "$Info ${purple}修改SVN配置${nocolor}"
    $csvnPath/csvn/bin/csvn-httpd install >/dev/null 2>&1
 
    /bin/cp -rf $csvnPath/csvn/data/certs/svnedge.crt $csvnPath/csvn/data/conf/server.crt >/dev/null 2>&1
    /bin/cp -rf $csvnPath/csvn/data/certs/svnedge.key $csvnPath/csvn/data/conf/server.key >/dev/null 2>&1
    #
    sed -i "/,'ServerSettings',/ s/0/1/g" $csvnPath/csvn/data/csvn-production-hsqldb.script
    sed -i "/,'ServerSettings',/ s/FALSE/TRUE/g" $csvnPath/csvn/data/csvn-production-hsqldb.script
    sed -i '/INSERT INTO SERVER VALUES/ s/(1,0/(1,1/g' $csvnPath/csvn/data/csvn-production-hsqldb.script
    sed -i "/INSERT INTO SERVER VALUES/ s/,18080,/,$csvnPort,/g" $csvnPath/csvn/data/csvn-production-hsqldb.script
    sed -i "/INSERT INTO SERVER VALUES/ s/,80,/,$csvnPort,/g" $csvnPath/csvn/data/csvn-production-hsqldb.script
    sed -i '/INSERT INTO SERVER VALUES/ s/FALSE,NULL,NULL,FALSE,FALSE/FALSE,NULL,NULL,TRUE,FALSE/g' $csvnPath/csvn/data/csvn-production-hsqldb.script
    hostName=`hostname`
    sed -i "/INSERT INTO SERVER VALUES/ s/$hostName/$ipaddr/g" $csvnPath/csvn/data/csvn-production-hsqldb.script
    
    #密码强度
    sed -i 's/^password.policy.strong=.*/password.policy.strong=false/g' $csvnPath/csvn/data/conf/security.properties >/dev/null 2>&1
    sed -i 's/^password.policy.min.length=.*/password.policy.min.length=6/g' $csvnPath/csvn/data/conf/security.properties >/dev/null 2>&1
    
    chown -R $csvnUser:$csvnUser $csvnPath/csvn/
    chown root:$csvnUser $csvnPath/csvn/lib/httpd_bind/httpd_bind
    chmod u+s $csvnPath/csvn/lib/httpd_bind/httpd_bind
    
    echo -e "$Info ${purple}启动CSVN管理控制台${nocolor}"
    /etc/init.d/csvn start
    kill `ps aux |grep $csvnPath/csvn/bin/httpd|grep -v grep|awk '{print $2}'` >/dev/null 2>&1
    echo -e "$Info ${purple}启动SVN服务${nocolor}"
    /etc/init.d/csvn-httpd start

    #判断是否启动
    UserUID=`cat /etc/passwd|grep "^$csvnUser:"|awk -F":" '{print $3}'`
    pass_info=
    if [ -n "$UserUID" -a "$csvnUser" != "root" ];then
        pass_info="$csvnUser用户密码为：$csvnUserPw，请牢记或修改！"
    fi
    
    csvn_control_status=`ps aux |grep wrapper|grep java|grep $csvnUser|grep $csvnPath/csvn/bin|grep -v grep`
    if [ "$PortCheck" == "Yes" ];then
        csvn_status=`$listen_cmd |grep ":$csvnPort "`
    else
        csvn_status=`ps aux |grep "$csvnPath/csvn/bin/httpd -f "|grep -v grep`
    fi
    svnURL=
    if [ "$csvnPort" == "443" ];then
        svnURL="https://$ipaddr/svn"
    else
        svnURL="https://$ipaddr:$csvnPort/svn"
    fi
    
    if [[ -n $csvn_control_status && -n $csvn_status ]];then
        echo "csvn安装成功" >>$logs_file
        echo -e "$Info
------------------------------------
csvn安装成功！！！
管理控制台地址：http://$ipaddr:$csvnPort_control/csvn
默认管理用户密码为：admin/admin
SVN地址：$svnURL
$pass_info"
    elif [[ -n $csvn_control_status && -z $csvn_status ]];then
        echo -e "$Warn
------------------------------------
csvn管理服务启动成功，SVN服务启动失败！
管理控制台地址：http://$ipaddr:$csvnPort_control/csvn
默认管理用户密码为：admin/admin
请使用$csvnPath/csvn/bin/csvn-httpd start命令启动SVN服务以排查错误
$pass_info"
    else
        echo -e "$Error
csvn安装失败！！！
请使用$csvnPath/csvn/bin/csvn start启动管理服务以排查错误" 
    fi
    anykeyback
}